package cn.edu.tju.elm.repository;

import cn.edu.tju.elm.model.Credit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface CreditRepository extends JpaRepository<Credit, Long> {

    /**
     * 根据用户ID获取所有积分记录
     */
    List<Credit> findByUserId(Long userId);

    /**
     * 根据用户ID和渠道类型获取积分记录
     */
    List<Credit> findByUserIdAndChannelType(Long userId, Integer channelType);

    /**
     * 获取用户可用积分（未删除且未过期）
     */
    @Query("SELECT c FROM Credit c WHERE c.user.id = :userId AND c.deleted = false AND " +
            "(c.expiredTime IS NULL OR c.expiredTime > CURRENT_DATE)")
    List<Credit> findAvailableByUserId(@Param("userId") Long userId);

    /**
     * 获取用户积分总数
     */
    @Query("SELECT SUM(c.creditNum) FROM Credit c WHERE c.user.id = :userId")
    Integer sumCreditNumByUserId(@Param("userId") Long userId);
}
